var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var isPosting = false;
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
});
var oldData = '';
var isEdit = false;
Page({
  data: {
    uploadImg:[],
    uploadImgFiles:[],
    token:"",
    uid:0,
    minHeight:0,
    imgWH: 0,
    msgInitValue: ''
  },
  onLoad: function(data){
    oldData = '';
    isEdit = false;
    if(data.data) {//有数据传过来，说明是编
      wx.showLoading({
        title: '加载中',
      })
      oldData = JSON.parse(data.data);
      isEdit = true;
    }
    this.load();
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
      that.setData({
        uid: res.uid,
        token: res.token
      });
      }
    });
  },
  load:function(){
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          minHeight:res.windowHeight-40,
          imgWH:(res.windowWidth-18)/4-12
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(isEdit){
      var photoArray = [];
      if (oldData.photos) {
        photoArray = oldData.photos.split(',');
      }
      this.setData({
        msgInitValue: oldData.message,
        uploadImg: photoArray
      })
      wx.hideLoading();
    }
  },

  releaseSubmit: function(e){
    if (isPosting) {
      //app.dialog('发布中，请稍等', 'loading');
      return false;
    }
    isPosting = true;
    var content = e.detail.value.content;//内容
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var files = this.data.uploadImgFiles;//选择的图片  图片的本地文件列表，每一项是一个 File 对象
    //上面两个看用哪个
    if(!content){
      app.dialog('请输入内容', 'loading');
      isPosting = false;
      return false;
    }
    if (photos.length == 0) {
      app.dialog('请上传图片', 'loading');
      isPosting = false;
      return false;
    }
    // wx.showLoading({ title: '发布中,请稍等' });
    wx.showLoading({ title: '发布中...' });
    //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
    var nowd = new Date();
    var nowm = nowd.getMonth() + 1;
    nowm = nowm.toString();
    if (parseInt(nowm) < 10) {
      nowm = '0' + nowm;
    }
    var nowda = nowd.getDate();
    nowda = nowda.toString();
    if (parseInt(nowda) < 10) {
      nowda = '0' + nowda;
    }
    var nowhour = nowd.getHours();
    nowhour = nowhour.toString();
    if (parseInt(nowhour) < 10) {
      nowhour = '0' + nowhour;
    }
    var action = "posttopic";
    if(isEdit){
      action = "edittopic";
    }
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + action + token);//私钥
    var data = {
      ac: action,
      topictype: 7,
      publickey: util.publiccode,
      privatekey: privatekey,
      uid: uid,
      postuid: uid,
      // topictitle: content,
      message:content,
      xcx:1,
      photos: this.data.uploadImg.map(function (item) { return item.replace('wxfile://tmp_', util.imgHost + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',')
    }
    if (isEdit) {
      data.topicid = oldData.id;
    }
    
    console.log("近况 params:", data);

    util.api({
      data:data,
      method:"POST",
      success:function(responseData){
        console.log(responseData);
        if(responseData.data.id){//你看是不是这个字段判断发布失败还是成功的
          isPosting = false;
          // wx.redirectTo({ url: "/pages/index/index?go=dongtai" });
          wx.reLaunch({ url: "/pages/index/index?go=dongtai" });
        }else{
          app.dialog('发布失败', 'loading');
          isPosting = false;
        }
      }
    });
  },
  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    var flie = this.data.uploadImgFiles;
    if (photos.length >= 9){
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function ({errMsg}) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });

    // wx.chooseImage({
    //   count: (9 - photos.length),
    //   success: function (res) {
    //     var tempFilePaths = res.tempFilePaths;
    //     var tempFiles = res.tempFiles;
    //     that.setData({
    //       uploadImg: tempFilePaths.concat(photos),
    //       uploadImgFiles: tempFilePaths.concat(flie)
    //     });
    //   }
    // });
  },
  deleteImg: function(e){
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index,1);
    this.setData({
      uploadImg:photos
    });
  }
})